import React, { useEffect, useState } from 'react';
import { connect } from 'umi';
import { Form, Table, Input, Card, Button, DatePicker, message, Divider } from 'antd';
import { utils } from 'vv-frontend-components';
import { eventTrack } from '@/utils/track';
import moment from 'moment';
// import isEmpty from 'lodash/isEmpty';
import LinkTo from '@/components/LinkTo';
import { history } from 'umi';
import isEmpty from 'lodash/isEmpty';
import CompanyDepart from '@/components/CompanyDepart';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import PageRouter from '@/components/PageRouter/PageRouter';
import authHelpr from '@/utils/auth/helper';
import Pagination from '@/components/Pagination';
import CancleEntry from './CancleEntry';
import EditDate from './EditDate';
import './index.less';
// AuthComponent AuthCode权限控制
// import AuthCode from '@/utils/auth/AuthCode';
// import AuthComponent from '@/utils/auth/AuthComponent';

const { checkCode } = authHelpr;
const { RangePicker } = DatePicker;
const List = ({ form, loading, entryManagement, dispatch, location, route }) => {
    // 我的入职与入职管理公用组件
    // mine: 我的入职  company: 入职管理
    const { path } = route;
    let typeJump = '';
    if (path === '/office/personnelManagement/onboardAndLeave/entryManagement') {
        typeJump = 'company';
    } else if (path === '/personal/portal/myOnboardAndLeave/myEntryManagement') {
        typeJump = 'mine';
    } else {
        throw new Error('未找到路径！请检查');
    }
    // 按钮权限控制
    // const { authCode } = new AuthCode(route.code);
    // 过滤高级搜索空格
    const { deepTrim } = utils;
    const { query } = location;
    const { pagination, entrymanaList: tableData } = entryManagement;
    // 获取登陆人
    const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
    // 获取参数
    const { getFieldsValue } = form;
    const { getFieldDecorator } = form;
    // 获取查询字段内容
    const getSearchData = pageNo => {
        // 方法自动获取高级搜索表单参数
        const { userName, companyDepart = {}, addtime } = getFieldsValue();
        // 接口传参参数
        const payload = {
            pageNo: pageNo || pagination.current,
            pageSize: pagination.pageSize,
            // 高级搜索字段
            companyCode: companyDepart?.companyId || user.companyId,
            departmentId: companyDepart.departmentId || '',
            searchName: userName || '',
            startTime: !isEmpty(addtime) && addtime[0] ? addtime[0].format('YYYY-MM-DD') : '',
            endTime: !isEmpty(addtime) && addtime[1] ? addtime[1].format('YYYY-MM-DD') : ''
        };
        return payload;
    };
    const [visible, setVisible] = useState(false); // 监听取消入职模态框
    const [isCancle, setIsCancle] = useState(false); // 监听取消入职模态框
    const [cancleDetail, setCancleDetail] = useState(''); // 监听当前操作取消入职详情
    // 接口请求
    const fetchList = (ctx = {}) => {
        const { pageNo = null } = ctx;
        dispatch(
            deepTrim({
                type: 'entryManagement/fetchEntrymanaList',
                payload: {
                    ...getSearchData(pageNo)
                }
            })
        );
    };
    // 分页功能
    const tableChange = paginations => {
        dispatch({
            type: 'entryManagement/save',
            payload: {
                pagination: {
                    ...entryManagement.pagination,
                    ...paginations
                }
            }
        });
    };
    // 列表项
    const columns = [
        {
            title: '姓名',
            dataIndex: 'talentName',
            key: 'talentName',
            width: 150,
            render(text, record) {
                if (typeJump === 'mine') {
                    return <span>{text}</span>;
                }
                return (
                    <span
                        style={{
                            display: 'inline-block',
                            maxWidth: 200,
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap',
                            verticalAlign: ' text-bottom'
                        }}
                        title={text}
                    >
                        {record.offerState === 'offerAccepted' && !checkCode('office:job:offer') ? (
                            <a
                                href="#"
                                onClick={e => {
                                    e.preventDefault();
                                    message.error('暂无权限');
                                }}
                            >
                                {text}
                            </a>
                        ) : (
                            <LinkTo
                                // 埋点
                                onClick={async (e, url) => {
                                    await eventTrack({
                                        eventName: 'personnel_management_onboardAndLeave_entry_detail_click',
                                        eventProps: {
                                            label: '入职管理-入职详情'
                                        }
                                    });
                                    history.push(url);
                                }}
                                to={
                                    record.offerState === 'offerAccepted'
                                        ? '/office/personnelManagement/recruit/offer/detail'
                                        : '/office/personnelManagement/onboardAndLeave/entryManagement/addEntry'
                                }
                                query={{
                                    offerCode: record.offerCode
                                }}
                            >
                                {text}
                            </LinkTo>
                        )}
                    </span>
                );
            }
        },
        {
            title: '公司',
            dataIndex: 'companyName',
            key: 'companyName',
            width: 150
        },
        {
            title: '部门',
            dataIndex: 'departmentName',
            key: 'departmentName',
            width: 150
        },
        {
            title: '就职职位',
            dataIndex: 'entryPostName',
            key: 'entryPostName'
        },
        {
            title: '预计入职日期',
            dataIndex: 'entryDate',
            key: 'entryDate',
            width: 200,
            render(text, record) {
                return (
                    <div>
                        <span>{text}</span>
                        {record.offerState === 'offerAccepted' ? (
                            <span>
                                {checkCode('office:personnel:progress:entry:edit') && (
                                    <a
                                        style={{ marginLeft: '16px' }}
                                        onClick={e => {
                                            e.preventDefault();
                                            setCancleDetail(record);
                                            setIsCancle(true);
                                        }}
                                        className="editData"
                                    >
                                        编辑
                                    </a>
                                )}
                            </span>
                        ) : null}
                        {record.extendedDays > 0 && record.offerState === 'offerAccepted' ? (
                            <div style={{ color: '#f00' }}>已超期{record.extendedDays}天</div>
                        ) : null}
                    </div>
                );
            }
        },
        {
            title: '操作人',
            dataIndex: 'updateUser',
            key: 'updateUser'
        },
        {
            title: '状态',
            dataIndex: 'offerStateName',
            key: 'offerStateName'
        },
        {
            title: '操作',
            dataIndex: '',
            key: '',
            width: 200,
            fixed: 'right',
            render(text, record) {
                // 两个页面公用 不需要限制code以及跳转路径不同--后又同步code
                if (typeJump === 'mine') {
                    return (
                        <div>
                            {record.offerState === 'offerAccepted' ? (
                                <div>
                                    {checkCode('office:personnel:progress:entry:view') && (
                                        <LinkTo
                                            to="/personal/portal/myOnboardAndLeave/addEntry"
                                            query={{
                                                offerCode: record.offerCode,
                                                action: 'edit'
                                            }}
                                            className="marginR dividingline"
                                        >
                                            办理入职
                                        </LinkTo>
                                        // <a
                                        //     className="marginR dividingline"
                                        //     href={`/personal/portal/myOnboardAndLeave/addEntry?offerCode=${record.offerCode}&action=edit`}
                                        // >
                                        //     办理入职
                                        // </a>
                                    )}
                                    <Divider type="vertical" style={{ color: '#e9e9e9' }} className="cancleEntry" />
                                    {checkCode('office:personnel:progress:entry:cancelentry') && (
                                        <a
                                            onClick={e => {
                                                e.preventDefault();
                                                setCancleDetail(record);
                                                setVisible(true);
                                            }}
                                            className="cancleEntry"
                                        >
                                            取消入职
                                        </a>
                                    )}
                                </div>
                            ) : (
                                <div>
                                    {checkCode('office:personnel:progress:entry:detail') && (
                                        <LinkTo
                                            onClick={async (e, url) => {
                                                // 埋点
                                                await eventTrack({
                                                    eventName: 'personal_my_entry_operator_click',
                                                    eventProps: {
                                                        label: '我的入职-操作-详情'
                                                    }
                                                });
                                                history.push(url);
                                            }}
                                            to="/personal/portal/myOnboardAndLeave/addEntry"
                                            query={{
                                                offerCode: record.offerCode
                                            }}
                                            className="marginR dividingline"
                                        >
                                            详情
                                        </LinkTo>
                                        // <a
                                        //     className="marginR dividingline"
                                        //     href={`/personal/portal/myOnboardAndLeave/addEntry?offerCode=${record.offerCode}`}
                                        // >
                                        //     详情
                                        // </a>
                                    )}
                                </div>
                            )}
                        </div>
                    );
                }
                return (
                    <div>
                        {record.offerState === 'offerAccepted' ? (
                            <div>
                                {checkCode('office:personnel:progress:entry:view') && (
                                    <LinkTo
                                        to="/office/personnelManagement/onboardAndLeave/entryManagement/addEntry"
                                        query={{
                                            offerCode: record.offerCode,
                                            action: 'edit'
                                        }}
                                        className="marginR dividingline"
                                    >
                                        办理入职
                                    </LinkTo>
                                    // <a
                                    //     className="marginR dividingline"
                                    //     href={`/office/personnelManagement/onboardAndLeave/entryManagement/addEntry?offerCode=${record.offerCode}&action=edit`}
                                    // >
                                    //     办理入职
                                    // </a>
                                )}
                                <Divider type="vertical" style={{ color: '#e9e9e9' }} className="cancleEntry" />
                                {checkCode('office:personnel:progress:entry:cancelentry') && (
                                    <a
                                        onClick={e => {
                                            e.preventDefault();
                                            setCancleDetail(record);
                                            setVisible(true);
                                        }}
                                        className="cancleEntry"
                                    >
                                        取消入职
                                    </a>
                                )}
                            </div>
                        ) : (
                            <div>
                                {checkCode('office:personnel:progress:entry:detail') && (
                                    <LinkTo
                                        onClick={async (e, url) => {
                                            // 埋点
                                            await eventTrack({
                                                eventName: 'personnel_management_onboardAndLeave_entry_operator_click',
                                                eventProps: {
                                                    label: '入职管理-操作-详情'
                                                }
                                            });
                                            history.push(url);
                                        }}
                                        to="/office/personnelManagement/onboardAndLeave/entryManagement/addEntry"
                                        query={{
                                            offerCode: record.offerCode
                                        }}
                                        className="marginR dividingline"
                                    >
                                        详情
                                    </LinkTo>
                                    // <a
                                    //     className="marginR dividingline"
                                    //     href={`/office/personnelManagement/onboardAndLeave/entryManagement/addEntry?offerCode=${record.offerCode}`}
                                    // >
                                    //     详情
                                    // </a>
                                )}
                            </div>
                        )}
                    </div>
                );
            }
        }
    ];
    const resetForm = () => {
        // 埋点
        eventTrack({
            eventName: 'personnel_management_onboardAndLeave_entry_reset_click',
            eventProps: {
                label: '入职管理-重置'
            }
        });
        form.resetFields();
        history.push({
            query: {}
        });
    };
    // 组件卸载时候 清空表单请求参数（高级搜索内容、分页、排序字段）
    useEffect(
        () => () => {
            // resetForm();
            form.resetFields();
            dispatch({
                type: 'entryManagement/save',
                payload: {
                    pagination: {
                        total: 0,
                        pageSize: 10,
                        current: 1
                    },
                    entrymanaList: []
                }
            });
        },
        []
    );
    // 每当分页数、页面条数、排序、筛查项改变时均应该重新请求表格数据
    useEffect(() => {
        fetchList();
    }, [pagination.pageSize, pagination.current]);
    const pageBody = (
        <>
            <Card title={typeJump === 'mine' ? '我的入职' : '待入职员工'} bordered={false}>
                {typeJump !== 'mine' ? (
                    <Form
                        layout="inline"
                        style={{ marginBottom: 12 }}
                        onSubmit={e => {
                            e.preventDefault();
                            fetchList({ pageNo: 1 });
                        }}
                    >
                        <Form.Item label="员工姓名">
                            {getFieldDecorator('userName', {
                                initialValue: query.searchName || ''
                            })(<Input placeholder="请输入员工姓名" />)}
                        </Form.Item>
                        <Form.Item label="公司部门">
                            {getFieldDecorator('companyDepart', {
                                initialValue: {
                                    companyId: query.companyId,
                                    departmentId: query.departmentId
                                }
                                // 按钮权限暂未开发  先写死
                            })(<CompanyDepart />)}
                        </Form.Item>
                        <Form.Item label="入职日期">
                            {getFieldDecorator('addtime', {
                                // initialValue: typeof query.addtime !== 'undefined' ? query.addtime : undefined
                                initialValue: [
                                    query.startTime ? moment(query.startTime) : undefined,
                                    query.endTime ? moment(query.endTime) : undefined
                                ]
                            })(<RangePicker format="YYYY-MM-DD" />)}
                        </Form.Item>
                        <Form.Item>
                            <Button
                                htmlType="submit"
                                // 埋点
                                onClick={() => {
                                    // const { userName, companyDepart = {}, addtime } = getFieldsValue();
                                    eventTrack({
                                        eventName: 'personnel_management_onboardAndLeave_entry_search_click',
                                        eventProps: {
                                            label: '入职管理-查询',
                                            key_words: JSON.stringify(getFieldsValue())
                                        }
                                    });
                                    history.push({
                                        query: {
                                            ...query,
                                            ...getSearchData()
                                        }
                                    });
                                    fetchList({ pageNo: 1 });
                                }}
                            >
                                查询
                            </Button>
                            <Button style={{ marginLeft: 8 }} onClick={resetForm}>
                                重置
                            </Button>
                        </Form.Item>
                    </Form>
                ) : null}
                <div className="entry">
                    <Table
                        bordered={false}
                        columns={columns}
                        loading={loading.models.entryManagement}
                        scroll={{ x: 'max-content' }}
                        dataSource={tableData}
                        rowKey="entrymanagement"
                        onChange={tableChange}
                        pagination={false}
                    />
                    <Pagination {...pagination} onChange={tableChange} />
                </div>
            </Card>
            <CancleEntry
                Visible={visible}
                params={{ cancleDetail, fetchList }}
                // 关闭模态框
                onOk={() => setVisible(false)}
                onCancel={() => setVisible(false)}
            />
            <EditDate
                Visible={isCancle}
                params={{ cancleDetail, fetchList }}
                // 关闭模态框
                onOk={() => setIsCancle(false)}
                onCancel={() => setIsCancle(false)}
            />
        </>
    );
    return (
        <PageHeaderWrapper>
            {typeJump === 'mine' ? <PageRouter type="myOnboardAndLeave">{pageBody}</PageRouter> : pageBody}
        </PageHeaderWrapper>
    );
};
export default connect(({ entryManagement, loading }) => ({
    entryManagement,
    loading
}))(Form.create()(List));
